using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using MaskData;

namespace DBProxy
{
	public class TreeNodeBuilder
	{
		public NavigateTreeNode BuildTree(ITreeNodeQuery treeNodeQuery)
		{
			List<NavigateTreeNode> treeNodes = treeNodeQuery.GetTreeNodes();
			Dictionary<Int32, NavigateTreeNode> treeNodesMap = new Dictionary<int, NavigateTreeNode>();
			foreach(NavigateTreeNode treeNode in treeNodes)
			{
				treeNodesMap[treeNode.TreeNodeID] = treeNode;
			}

			NavigateTreeNode root = null;
			int rootCount = 0;
			foreach (KeyValuePair<Int32, NavigateTreeNode> pairNode in treeNodesMap)
			{
				pairNode.Value.Parent = treeNodesMap[pairNode.Value.ParentID];
				if (pairNode.Value.ParentID != pairNode.Key)
					treeNodesMap[pairNode.Value.ParentID].AddChild(pairNode.Value);
				if (pairNode.Value.ParentID == pairNode.Value.TreeNodeID)
				{ 
					root = pairNode.Value;
					rootCount++;
				}
			}
			Debug.Assert(rootCount == 1);
			Debug.Assert(root != null);

			return root;
		}
	}
}
